/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.merak.core.text.json.jsonfiers;

import org.merak.core.text.json.JsonContext;

public class StringJsonfier extends Jsonfier {

	//~ Static ///////////////////////////////////////////////////////////////////
	//****************************************************************************
	private static final String[] charIndex = new String[128];

	//~ Static Constructor ///////////////////////////////////////////////////////
	//****************************************************************************
	static {

		for (char c=0; c<charIndex.length; c++) {
			// Ensures non-printable characters will be printed as 4-hex-digits
			charIndex[c] = String.valueOf(c).replaceAll(
					"\\p{Cntrl}", String.format ("\\\\u%04x", (int)c)
			);
		}
		/* Ensures non-printable characters with special escape sequence will be
		 * printed as special escape */
		charIndex['\"'] = "\\\"";
		charIndex['\\'] = "\\\\";
		charIndex['\b'] = "\\b";
		charIndex['\f'] = "\\f";
		charIndex['\n'] = "\\n";
		charIndex['\r'] = "\\n";
		charIndex['\t'] = "\\t";

	}
	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	@Override
	public final void render(Object object,JsonContext context) throws Exception {

		// Base Case: Not Null
		if(object == null) {
			context.getBuffer().append("null");
			return;
		}

		StringBuffer json   = context.getBuffer();
		String		 string = object.toString();
		int    		 length = string.length();

		json.append('"');
		for (int i=0; i<length; i++) {
			this.appendChar(string.charAt(i),json);
		}
		json.append('"');

	}
	//****************************************************************************
	private final void appendChar(char ch,StringBuffer json) {

		if (ch >= charIndex.length) {
			json.append(ch);
		}
		else {
			json.append(charIndex[ch]);
		}

	}
	//****************************************************************************

}
